package demo23.v2;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

class workThread extends Thread{
    private PriorityBlockingQueue<MyTimerTask> queue;
    workThread(PriorityBlockingQueue<MyTimerTask> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true){
            try {
                MyTimerTask task = queue.take();
                if (task.runAt <= System.currentTimeMillis()) {
                    task.target.run();
                    continue;
                } else {
                    long delay = task.runAt - System.currentTimeMillis();
                    TimeUnit.SECONDS.sleep(delay);
                }
            } catch (InterruptedException exc){

            }
        }
    }
}

public class MyTimer {
    PriorityBlockingQueue<MyTimerTask> queue;
    Thread workThread;

    public MyTimer(){
        workThread = new workThread(queue);
        workThread.start();
    }

    public void schedule(MyTimerTask task, long delay){
        task.runAt = System.currentTimeMillis() + delay;
        queue.put(task);
        // TODO: 需要唤醒线程
    }
}
